﻿using Microsoft.EntityFrameworkCore;
using ZeroSum.Domain.Repositories;
using ZeroSum.Extend.EFCore.MySql.Extensions;
using ZeroSum.Plugin.Authorization.Datas.Services.Users;
using ZeroSumZSA.Core.Aggregates.UserAggregate;

namespace ZeroSumZSA.Core.DomainServices.Users;

public class UserDomainService : UserBaseDomainService<User>, IUserDomainService
{
    public UserDomainService(IRepository<User, long> userRepository) : base(userRepository)
    {
    }

    public Task<IList<User>> Query(string? keyword, int page, int size)
    {
        var query = GetQueryBy(keyword);
        return UserRepository.GetListAsync(query.Paged(page, size));
    }

    public async Task<IList<long>> GetRoleIdsByUserId(long userId)
    {
        var query = QueryByEntity<User>.Of(q => q.Where(x => x.Id == userId).Include(x => x.Roles));

        var user = await UserRepository.GetAsync(query);
        return user == null ? new List<long>() : user.Roles!.Select(x => x.Id).ToList();
    }

    public Task<int> Count(string? keyword)
    {
        var query = GetQueryBy(keyword);
        return UserRepository.CountAsync(query);
    }

    private static QueryByEntity<User> GetQueryBy(string? keyword)
    {
        var isEmpty = !string.IsNullOrEmpty(keyword?.Trim());

        IQueryable<User> Func(IQueryable<User> query)
        {
            return query.WhereIf(isEmpty,
                u => EF.Functions.Like(u.Name!, $"%{keyword!.Trim()}%") ||
                     EF.Functions.Like(u.Account!, $"%{keyword.Trim()}%")).OrderBy(x => x.Id);
        }

        var query = QueryByEntity<User>.Of(Func);
        return query;
    }
}